using System;
using System.Web;
using System.IO;

namespace Library.WebControls.SimpleUpload {
	public class FileUploadCompleteEventArgs : Library.WebControls.CustomCallbackEventArgs {
		public FileUploadCompleteEventArgs(string parameter) : base(parameter) { }
		public HttpPostedFile PostFile { get; internal set; }
		public string UploadedServerFilePath { get; internal set; }
		private string _clientFileName;
		public string ClientFileName {
			get {
				if (_clientFileName == null) {
					if (PostFile != null) {
						_clientFileName = Path.GetFileName(PostFile.FileName);
					}
				}

				return _clientFileName;
			}

			internal set { _clientFileName = value; }
		}

		public byte[] ContentFile {
			get {
				if (PostFile == null) {
					if (String.IsNullOrEmpty(UploadedServerFilePath))
						return new byte[0];

					using (var file = File.OpenRead(UploadedServerFilePath)) {
						return ConvertStream(file);
					}
				}

				return ConvertStream(PostFile.InputStream);
			}
		}

		private static byte[] ConvertStream(Stream stream) {
			//var ms = new MemoryStream((int)stream.Length);
			if (stream.CanSeek) stream.Seek(0, SeekOrigin.Begin);
			//const int chunk = 1024 * 10;
			var bytes = new byte[stream.Length];
			int numBytesToRead = (int)stream.Length;
			int numBytesRead = 0;
			while (numBytesToRead > 0) {
				// Read may return anything from 0 to numBytesToRead. 
				int n = stream.Read(bytes, numBytesRead, numBytesToRead);

				// Break when the end of the file is reached. 
				if (n == 0)
					break;

				numBytesRead += n;
				numBytesToRead -= n;
			}

			return bytes;
		}
	}
}
